/**
 * Copyright (c) Martijn Grootens (m.e.grootens@student.utwente.nl), 
 * University of Twente.
 * Created july 2012.
 *
 * This file is part of dbcleaner.
 * 
 * dbcleaner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * dbcleaner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with dbcleaner.  If not, see <http://www.gnu.org/licenses/>.
 */

package dbcleaner.core.fix;

import java.io.*;
import java.util.*;
import dbcleaner.core.dbentries.*;
import dbcleaner.core.parse.*;
import dbcleaner.core.tags.*;

/**
 * Fixing the tags...
 */
public class TagFixer {
    
    
    /**
     * Return entry with fixed tags
     */
    public static void fix_tags(Entry e, TagList sense, TagList nonsense) {
        
        // fetch tags that were scanned
        String tags = e.get_tags_from_extra();
        
        
        // if there are tags
        if (tags != null) {
            
            // remove all spaces
            tags = tags.replaceAll(" ", "");
            
            // comment out old tags
            e.comment_tags_from_extra();
            
            // split tags
            String[] split = tags.split(",");
            int num = split.length;
            
            for (int ii=0; ii<num; ++ii) {
                                
                //check if nonsense does NOT contain the tag
                if (!nonsense.contains(split[ii])) {
                    
                    // try and fetch tag from sense list
                    Tag t = sense.get_tag(split[ii]);
                    
                    if (t!=null)
                        e.add_tag(t);
                    else {
                        e.add_tag(new Tag(split[ii]));
                        System.out.println("allowed new tag: " + split[ii]);
                    }
                }
                
            }
            
        }
        
    }
    
    /**
     * fix all tags in a DataBase
     */
    public static void fix_tags(DataBase db,  TagList sense, TagList nonsense) {
        
        for (Entry e : db.get_entries()) {
            fix_tags(e,sense,nonsense);
        }
                
    }
    
}